<template>
  <div class="footer-container">
      <footer id="footer" :class="{active: showFooterFlag}">
        <div class="footer-left">
          <i id='msg-choose-img' class="mui-icon" style="font-size: 28px;"></i>
        </div>
        <div class="footer-center">
          <div id='msg-text'
          @keyup="editFocusFun"
          @focus="editFocusFun"
          class='input-text'
          contenteditable="true"
          ref="msgText">
          </div>
        </div>
        <!--表情点击出现选择表情的界面-->
        <div class="emoji" id='emoji'></div>
        <!--发送或者选择更多按钮-->
        <div class="footer-right">
          <!--如果输入框没有输入内容就显示该按钮，该按钮点击能显示其他的功能-->
          <span class="mui-icon mui-icon-plus morework" v-if="!showSendFlag"></span>
          <!--如果输入框已经有输入的内容，就显示发送字眼-->
          <span
          id='msg-send-text'
          v-else
          :class="{sendText: showSendFlag}"
          @click="sendText" >发送</span>
        </div>
        <!--显示系统表情界面-->
        <div id="bottomPopover"
        class="mui-popover mui-popover-bottom"
        :class="{active: showEmojiFlag}">
          <div class="mui-scroll-wrapper">
            <div class="mui-scroll img-container">
              <img :data-imgflag="'ee_'+i+'.png'"
              :src="require('../../../../static/face/ee_'+i+'.png')"
              alt=""
              v-for="i in 35" :key="i" >
            </div>
          </div>
        </div>
        <!--更多选择-->
        <div id="moreChoose" :class="{active: showMoreChoose}" >
          <div class="mui-slider moreChooseSlide">
            <div class="mui-slider-group">
              <div class="mui-slider-item">
                <div class="allImg" data-action='album'>
                  <div class="itemImg">
                    <span class="mui-icon mui-icon-image"></span>
                    <!--multiple="multiple"可以支持多个文件的选择-->
                    <input type="file" id="chooseImg" multiple="multiple" @change="sendImgTest"/>
                  </div>
                  <span>相册</span>
                </div>

                <div class="allImg allImg1" data-action='voice'>
                  <div class="itemImg">
                    <span class="mui-icon mui-icon-mic"></span>
                  </div>
                  <span>语音</span>
                </div>
                <div class="allImg allImg1" data-action='video'>
                  <div class="itemImg">
                    <span class="mui-icon mui-icon-videocam"></span>
                  </div>
                  <span>视频</span>
                </div>
                <div class="allImg allImg1" data-action='location'>
                  <div class="itemImg">
                    <span class="mui-icon mui-icon-location"></span>
                  </div>
                  <span>位置</span>
                </div>
                <div class="allImg allImg1" data-action='camera'>
                  <div class="itemImg">
                    <span class="mui-icon mui-icon-camera"></span>
                  </div>
                  <span>相机</span>
                </div>
                <div class="allImg allImg" data-action='card'>
                  <div class="itemImg">
                    <span class="mui-icon-extra mui-icon-extra-card"></span>
                  </div>
                  <span>明信片</span>
                </div>
                <div class="allImg" data-action='file'>
                  <div class="itemImg">
                    <span class="mui-icon-extra mui-icon-extra-topic"></span>
                    <input type="file" id="chooseFile" multiple="multiple" @change="sendFiles"/>
                  </div>
                  <span>文件</span>
                </div>
                <div class="allImg allImg1" data-action='love'>
                  <div class="itemImg">
                    <span class="mui-icon-extra mui-icon-extra-heart"></span>
                  </div>
                  <span>收藏</span>
                </div>
              </div>
              <div class="mui-slider-item">
                具体内容2
                具体内容2
                具体内容2
                具体内容2
                具体内容2
                具体内容2
              </div>
            </div>
          </div>
        </div>
      </footer>
  </div>
</template>

<script>
  import {mapGetters, mapState, mapActions} from 'vuex'
  export default {
    props: {
      type: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        // 输入框的内容
        msgtext: '',
        // 表情图片对应的特殊字符的数组
        emojiarr: [],
        // 展示表情div界面的标志，true为展示，否则不展示
        showEmojiFlag: false,
        // 更多选择界面的展示标志
        showMoreChoose: false,
        // 选中图片时触发发送标志, false:不显示发送  true的时候显示发送字体
        showSendFlag: false,
        // 整个底部，true的时候，zai上面，false的时候，呆在下面
        showFooterFlag: false
      }
    },
    created() {
      console.log(this.currentLoginUser, '当前登录用户')
      // 现在这里没有什么用，建立数据库之后，就从这里获取
      // this.getEmojiUrl()
      // 单聊贴图发送
      // document.addEventListener('paste', function (e) {
      //   if (e.clipboardData && e.clipboardData.types) {
      //     if (e.clipboardData.items.length > 0) {
      //       console.log(e.clipboardData.items[0].type, /^image\/\w+$/.test(e.clipboardData.items[0].type))
      //       if (/^image\/\w+$/.test(e.clipboardData.items[0].type)) {
      //         var blob = e.clipboardData.items[0].getAsFile()
      //         var url = window.URL.createObjectURL(blob)
      //         // 生成本地消息id
      //         var id = this.$imconn.getUniqueId()
      //         // 创建图片消息
      //         /* eslint-disable-next-line */
      //         var msg = new this.$webim.message('img', id)
      //         msg.set({
      //           apiUrl: this.$webim.config.apiURL,
      //           file: {data: blob, url: url},
      //           // 接收消息对象
      //           to: 'username',
      //           roomType: false,
      //           chatType: 'singleChat',
      //           onFileUploadError: function (error) {
      //             console.log('Error', error)
      //           },
      //           onFileUploadComplete: function (data) {
      //             console.log('Complete')
      //           },
      //           success: function (id) {
      //             console.log('Success')
      //           }
      //         })
      //         this.$imconn.send(msg.body)
      //       }
      //     }
      //   }
      // })
    },
    mounted() {
      this.init()
      console.log('环信截取后的id，当前的聊天用户', this.getCurrentUserChatSplitedId)
    },
    computed: {
      ...mapGetters(['getCurrentUserChatSplitedId', 'getCurrentChatUsername']),
      ...mapState(['currentChatUserId', 'currentLoginUser', 'currentChatGroup'])
    },
    watch: {
      showFooterFlag(newVal) {
        // 改变聊天框的底部高度
        this.$emit('chagemsg', newVal)
      }
    },
    methods: {
    //   ...mapMutations({
    //     setMessageList: SET_MESSAGE_LIST
    //   }),
      ...mapActions(['setDbMessageListAS', 'sendFile']),
      // 用以每次拼接成字符串本地发送的
      replaceImg(str) {
        // 返回输入的文字和表情的特殊字符组成的字符串
        while (str.indexOf('<') !== -1) {
          let start = str.indexOf('<')
          let end = str.indexOf('>', start)
          str = str.slice(0, start) + this.findKeyText(this.emojiarr.pop()) + str.slice(end + 1)
        }
        return str
      },
      // 输入框获取焦点时候的函数
      editFocusFun() {
        // 输入框获取焦点函数，按下键盘函数， 通过改变this.showSendFlag,动态修改发送的状态
        // console.log('focus or keydown')
        this.msgtext = this.$refs.msgText.innerHTML || ''
        // console.log(this.$refs.msgText.innerHTML)
          // 如果输入框有内容的话，就显示发送字眼
        if (this.msgtext) {
          this.showSendFlag = true
        } else {
          this.showSendFlag = false
        }
        // 只要获取到焦点，就不展示这些
        this.showMoreChoose = false
        this.showFooterFlag = false
        // this.$emit('chagemsg', newVal)
      },
      // 初始化你函数
      init() {
        const self = this
        self.$immui.init({
          gestureConfig: {
            tap: true
          }
        })
        self.$immui('.mui-scroll-wrapper').scroll({
          deceleration: 0.0005,
          indicators: false
        })
        // 表情点击之后，显示表情界面
        self.$immui('.footer-container').on('tap', '.emoji', function (e) {
          // console.log(1111, 'oooooooooooooooo')
          // 点击表请包之后，根据标志判断是否要添加该类
          // console.log(self.showEmojiFlag, '展示表情界面的标志')
          if (!self.showEmojiFlag) {
            // 点击表情之后，让输入框失去焦点
            self.$refs.msgText.blur()
            self.showFooterFlag = true
            self.showEmojiFlag = true
            self.showMoreChoose = false
          } else {
            self.showFooterFlag = false
            self.showEmojiFlag = false
          }
          // console.log(self.showEmojiFlag)
        })
        // 每一个表情点击之后添加到输入框
        self.$immui('.img-container').on('tap', 'img', function (e) {
          // 表请点击的时候创建节点插入输入框
          var imgNode = document.createElement('img')
          let src = this.getAttribute('src')
          imgNode.setAttribute('src', src)
          var edit = document.getElementById('msg-text')
          edit.appendChild(imgNode)
          // 表情点击之后，找到对应的特殊字符，添加到要发送的消息的变量中
          let id = this.getAttribute('data-imgflag')
          self.emojiarr.unshift(id)
          // 点击表请之后，隐藏表情界面,但是表情界面初始化还原
          self.showEmojiFlag = true
          self.showFooterFlag = false
          self.showEmojiFlag = false
          moveEnd(edit)
        })
        // 将光标移动到编辑框的最后
        function moveEnd(obj) {
          obj.focus()
          var len = obj.innerText.length
          if (document.selection) {
            let sel = document.selection.createRange()
            sel.moveStart('character', len)
            sel.collapse()
            sel.select()
          } else {
            /* IE11 特殊处理 */
            let sel = window.getSelection()
            var range = document.createRange()
            range.selectNodeContents(obj)
            range.collapse(false)
            sel.removeAllRanges()
            sel.addRange(range)
          }
        }
        // 选择更多的点击事件
        self.$immui('.footer-container').on('tap', '.morework', function (e) {
          console.log('点击更多选择')
          // 点击选择更多的+号时候，将显示表情的标志置为false
          if (!self.showMoreChoose) {
            // 点击表情之后，让输入框失去焦点，同时切换项目
            self.$refs.msgText.blur()
            self.showFooterFlag = true
            self.showMoreChoose = true
            self.showEmojiFlag = false
            // console.log(mui)
            self.$immui('.moreChooseSlide').slider({
              interval: 0
            })
          } else {
            self.showFooterFlag = false
            self.showMoreChoose = false
          }
          // self.showMoreChoose = !self.showMoreChoose
        })
        // 更多选择里面界面的没有自动轮播的轮播图 //自动轮播周期，若为0则不自动播放，默认为0；
        self.$immui('.mui-slider').slider({
          interval: 0
        })
        // 选择更多里面每一项的点击事件
        self.$immui('.footer-container').on('tap', '.allImg1', function (e) {
          let action = this.getAttribute('data-action')
          console.log(this.getAttribute('data-action'), action)
          if (action === 'voice') {
          } else if (action === 'voide') {
          } else if (action === 'location') {
          } else if (action === 'camera') {
          } else if (action === 'card') {
          } else if (action === 'file') {
            console.log(action)
          } else if (action === 'love') {
          }
          setTimeout(() => {
            self.showFooterFlag = false
            self.showMoreChoose = false
            self.showEmojiFlag = false
          }, 100)
        })
      },
      findKeyText(id) {
        var self = this
        for (let key in self.$webim.Emoji.map) {
          if (self.$webim.Emoji.map[key] === id) {
            return key
          }
        }
        return ''
  },
      // 发送文本消息函数
      sendText() {
        var self = this
        // 点击发送，当在发送图片的时候，这里需要区分发送图片文本文件还是音频
        // if (this.showSendFlag) {
        //   this.showSendFlag = false
        //   this.sendPrivateImg()
        //   return
        // }
        document.getElementById('msg-text').focus()
        let text = ''
        let to = ''
        let roomType = false
        // 单聊发送文本消息
        // 生成本地消息id
        let id = self.$imconn.getUniqueId()
        // 创建文本消息
       /* eslint-disable-next-line */
        let msg = new self.$webim.message('txt', id)
        // 单聊
        if (this.type === 'chat') {
          text = {
            msg: document.getElementById('msg-text').innerHTML,
            time: new Date().getTime(),
            read: true,
            self: true
          }
          to = self.getCurrentUserChatSplitedId
          roomType = false
          msg.body.chatType = 'singleChat'
          // console.log(this.type)
        } else if (this.type === 'groupchat') {
          // 群聊
          // console.log(this.type)
          text = {
            msg: document.getElementById('msg-text').innerHTML,
            time: new Date().getTime(),
            headicon: self.currentLoginUser.headiocn || self.$imHeadIcon,
            read: true,
            self: true
          }
          to = self.currentChatGroup.id
          roomType = false
          msg.setGroup('groupchat')
        } else if (this.type === 'chatroom') {
          // 聊天室
          console.log(this.type)
          text = {
            msg: document.getElementById('msg-text').innerHTML,
            time: new Date().getTime(),
            headicon: self.currentLoginUser.headiocn || self.$imHeadIcon,
            read: true,
            self: true
          }
          // to没有设置****
          roomType = true
          msg.setGroup('groupchat')
        }
        console.log(text, to, this.type, '发送消息以及要发送的对象')
        msg.set({
          // 要发送的消息内容，包括字符串
          msg: self.replaceImg(document.getElementById('msg-text').innerHTML || ''),
          // 接收消息对象（用户id）
          to: to,
          roomType: roomType,
          success: function (id, serverMsgId) {
            console.log('send private text Success', id, serverMsgId)
            // 消息发送成功后清空输入框
            document.getElementById('msg-text').innerHTML = ''
            // self.sendmsgtext = ''
            self.msgtext = ''
            // 当消息发送成功之后设置发送字体不显示
            self.showSendFlag = false
            self.emojiarr = []
            self.sendextAction(text)
            /*
            let data = {}
            // console.log(data)
            data['id'] = self.currentChatUserId.id
            // 通过id查找好友列表里面的用户名称
            data['name'] = self.getCurrentChatUsername.name
            // console.log(this.msgtext, '12312123')
            data['msg'] = {...text}
            console.log('拼接之后的data对象，将通过mutation修改消息列表', data)
            self.setDbMessageListAS(data)
            */
          },
          fail: function(e) {
            console.log('Send private text error')
          }
        })
        self.$imconn.send(msg.body)
      // 文本消息发送成功之后清空输入框的内容
        self.msgtext = ''
        self.showSendFlag = false
      },
      // 文本消息发送成功后的操作
      sendextAction(text) {
        const self = this
        if (this.type === 'chat') {
          // console.log('chat')
          let data = {}
          // console.log(data)
          data['id'] = self.currentChatUserId.id
          // 通过id查找好友列表里面的用户名称
          data['name'] = self.getCurrentChatUsername.name
          // console.log(this.msgtext, '12312123')
          data['msg'] = {...text}
          // console.log('拼接之后的data对象，将通过mutation修改消息列表', data)
          self.setDbMessageListAS(data)
        } else if (this.type === 'groupchat') {
          console.log('groupchat')
        }
      },
      // 单聊发送图片消息
      sendImgTest() {
        const self = this
       // 将图片信息转成64位进制的，存储到消息列表里面，以便显示图片
       let oFReader = new window.FileReader()
       let file = document.getElementById('chooseImg').files[0]
      //  console.log(file.size, '后期判断大小，如果超过10000，就以文件的形式上传')
       oFReader.readAsDataURL(file)
       oFReader.onload = function(e) {
          // console.log(e.target.result)
          let time = new Date().getTime()
          let text = {msg: e.target.result, time: time, read: true, self: true, type: 'img'}
          let data = {}
          data['id'] = self.currentChatUserId.id
              // 通过id查找好友列表里面的用户名称
          data['name'] = self.getCurrentChatUsername.name
          data['msg'] = {...text}
          console.log('发送图片：拼接之后的图片对象', data)
          self.setDbMessageListAS(data)
       }
        // 调用环信发送图片函数
        this.sendPrivateImg()
        /*
        let file = document.getElementById('chooseImg')
        console.log(getObjectURL(file.files[0]))
        let nodeImg = document.createElement('img')
        nodeImg.setAttribute('id', 'image')
        nodeImg.setAttribute('src', getObjectURL(file.files[0]))
        // console.log()
        document.getElementById('moreChoose').appendChild(nodeImg)
        // 获取文件路径后，放置img标签就可以显示了
        function getObjectURL(file) {
          var url = null
          window.URL = window.URL || window.webkitURL
          if (window.createObjcectURL !== undefined) {
            url = window.createOjcectURL(file)
          } else if (window.URL !== undefined) {
            url = window.URL.createObjectURL(file)
          } else if (window.webkitURL !== undefined) {
            url = window.webkitURL.createObjectURL(file)
          }
          return url
        }
        */
      },
      // 环信发送图片函数
      sendPrivateImg () {
        const self = this
        // 环信发送,条件：选中图片，并放到id=image的input里面去
        // 生成本地消息id
        var id = self.$imconn.getUniqueId()
        // 创建图片消息
        /* eslint-disable-next-line */
        var msg = new self.$webim.message('img', id)
        // 选择图片的input
        var input = document.getElementById('chooseImg')
        console.log(typeof input)
        // 将图片转化为二进制文件
        let file = this.$webim.utils.getFileUrl(input)
        console.log(file)
        var allowType = {
          'jpg': true,
          'gif': true,
          'png': true,
          'bmp': true
        }
        if (file.filetype.toLowerCase() in allowType) {
          var option = {
            apiUrl: self.$webim.config.apiURL,
            file: file,
            // 接收消息对象
            to: self.getCurrentUserChatSplitedId,
            roomType: false,
            chatType: 'singleChat',
            // 消息上传失败
            onFileUploadError: function () {
              console.log('onFileUploadError')
            },
            // 消息上传成功
            onFileUploadComplete: function () {
              console.log('onFileUploadComplete')
            },
            // 消息发送成功
            success: function () {
              console.log('Success')
            },
            flashUpload: self.$webim.flashUpload
          }
          msg.set(option)
          self.$imconn.send(msg.body)
        }
      },
      imgtest() {
        console.log('测试路由跳转')
        this.$router.push('/textimg')
      },
      sendFiles(e) {
        const self = this
        if (e.path) {
          // 后面修改单个文件上传为多个文件上传
          console.log(e.path[0].files.length, e.path[0].files)
          let obj = {
            // 文件前缀名字
            filePrefix: self.currentLoginUser.username + '/' + self.getCurrentUserChatSplitedId,
            name: e.path[0].files[0].name,
            size: e.path[0].files[0].size,
            time: e.path[0].files[0].lastModifiedDate,
            type: 'singleChat'
          }
          let file = document.getElementById('chooseFile')
          let blob = new Blob([file.files[0]], {'type': null})
          // console.log(blob)
          obj['file'] = blob
          // action上传文件
          self.sendFile(obj)
        }
      }
    /*
      getObjectURL(file) {
          var url = null
          window.URL = window.URL || window.webkitURL
          if (window.createObjcectURL !== undefined) {
            url = window.createOjcectURL(file)
          } else if (window.URL !== undefined) {
            url = window.URL.createObjectURL(file)
          } else if (window.webkitURL !== undefined) {
            url = window.webkitURL.createObjectURL(file)
          }
          return url
        }
      */
    }
  }
</script>

<style lang='scss' scoped>
footer {
  position: fixed;
  width: 100%;
  min-height: 50px;
  border-top: solid 1px #bbb;
  left: 0px;
  bottom: 0px;
  padding: 0px 50px;
  background-color: #fafafa;
  z-index: 12;
  &.active{
    transform: translateY(-200px);
  }
  .emoji{
    position: absolute;
    right: 45px;
    bottom: -8px;
    width: 35px;
    height: 50px;
    background: url("../../../assets/icon.png");
    background-position: -400px 66px;
  }
  .footer-left {
    position: absolute;
    width: 30px;
    height: 50px;
    left: 0px;
    bottom: 0px;
    text-align: center;
    vertical-align: middle;
    line-height: 100%;
    padding: 12px 4px;
    #msg-choose-img {
      width: 28px;
      height: 28px;
      background: url("../../../assets/icon.png");
      background-position: -195px 31px;
    }
  }
  .footer-right {
    position: absolute;
    width: 35px;
    height: 50px;
    right: 7px;
    bottom: 1px;
    text-align: center;
    vertical-align: middle;
    line-height: 100%;
    padding: 12px 0px;
    display: inline-block;
    &.sendText{
      background: green;
    }
    .morework{
      background: whitesmoke;
      color: black;
      font-size: 26px;
    }
    #msg-send-text{
      background: green;
      color: white;
    }
  }
  .footer-center {
    height: 100%;
    padding: 5px 0px;
    margin-left: -10px;
    margin-right: 30px;
  }
  #bottomPopover{
    width: 100%;
    height: 200px;
    position: absolute;
    bottom: -199px;
    left: 0;
    .img-container{
      padding-left: 15px;
      box-sizing: border-box;
    }
    /*padding-left: 20px;*/
    img {
      margin: 8px;
      width: 32px;
      height: 32px;
    }
    &.active{
      display: block;
      opacity: 1;
    }

  }
  #moreChoose{
    width: 100%;
    height: 200px;
    background-color: #f0efef;
    position: absolute;
    bottom: -199px;
    left: 0;
    display: none;
    &.active {
      display: block;
    }
    .mui-slider, .mui-slider-group {
      max-height: 200px;
    }
    .mui-slider .mui-slider-group .mui-slider-item{
      height: 200px;
      padding: 20px;
      display:flex ;
      flex-wrap: wrap;
    }
    .allImg{
      flex: 0 0 50px;
      width: 50px;
      height: 76px;
      text-align: center;
      position: relative;
      left: 0;
      top: 0;
      margin: 6px 15px;
      .itemImg {
        width: 50px;
        height: 50px;
        line-height: 54px;
        border-radius: 10px;
        background: rgba(255, 255, 255, 1);
        span {
          font-size: 28px;
          color: black;
        }
      }
      span {
        padding-top: 2px;
        font-size: 12px;
        color: rgb(49, 48, 48);
      }
      #chooseImg{
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
      }
      #chooseFile{
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
      }
    }
  }
}

.footer-center [class*=input] {
  width: 100%;
  height: 100%;
  border-radius: 5px;
}
.footer-center .input-text {
  background: #fff;
  border: solid 1px #ddd;
  padding: 10px !important;
  font-size: 16px !important;
  line-height: 18px !important;
  font-family: verdana !important;
  overflow: hidden;
}

footer .mui-icon {
  color: #000;
}
footer .mui-icon:active {
  color: #007AFF !important;
}
.footer-right span{
  color: #0062CC;
  line-height: 30px;
  display: inline-block;
  font-size: 14px;
  width: 120%;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}
</style>
